package com.sy.simpleegg.serialport.sycontroller

import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.serialport.base.BaseController
import com.sy.simpleegg.serialport.util.CRC16
import com.sy.simpleegg.serialport.util.MyFunc
import com.sy.simpleegg.util.ByteUtil
import org.cnbleu.serialport.SerialPort

abstract class SyBaseController(
    portName: String,
    baudrate: SerialPort.BAUDRATE,
    stopb: SerialPort.STOPB,
    datab: SerialPort.DATAB,
    parity: SerialPort.PARITY,
    speed: Long?
) : BaseController(portName, baudrate, stopb, datab, parity, speed) {

    private val TAG = javaClass.simpleName

    /**
     * 发送数据
     */
    private fun sendByte(dataBytes: ByteArray){
        try {
            val crcCode = CRC16.crc16Checkout(dataBytes)
            val result = ByteUtil.combineByteArray(dataBytes, crcCode)
            sendData(result, 0)
        }catch (e: Exception){
            logFile("sendByte 发送指令异常：${e.message}")
        }
    }

    /**
     * 出币指令 type=1 马达1出币 type=2 马达2出币 count 出币数量
     */
    fun outCoin(type: Int, count: Long){
        try {
            val cmdDefault: ByteArray? = when (type) {
                1 -> byteArrayOf(0x01, 0x10, 0x00, 0x33, 0x00, 0x05, 0x0A, 0x00, 0x02)
                2 -> byteArrayOf(0x01, 0x10, 0x00, 0x33, 0x00, 0x05, 0x0A, 0x00, 0x06)
                else -> null
            }

            val countHex = ByteUtil.decimal2fitHex(count, 16)
            val countBytes = MyFunc.HexToByteArr(countHex)
            val cmdNoCrc = ByteUtil.combineByteArray(cmdDefault!!, countBytes)

            sendByte(cmdNoCrc)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("")
        }
    }

    /**
     * 开始存币
     */
    fun startInCoin(){
        val cmdDefault = byteArrayOf(0x01, 0x10, 0x00, 0x6E, 0x00, 0x01, 0x02, 0x80.toByte(), 0x00, 0xCF.toByte(), 0x1E)
        sendByte(cmdDefault)
    }

    /**
     * 停止存币
     */
    fun stopInCoin(){
        val cmdDefault = byteArrayOf(0x01, 0x10, 0x00, 0x6E, 0x00, 0x01, 0x02, 0x00, 0x00)
        sendByte(cmdDefault)
    }

    /**
     * 重启
     */
    fun reboot(){
        val cmdDefault = byteArrayOf(0x01, 0x10, 0x00, 0x33, 0x00, 0x05, 0x0A, 0x00, 0x0A)
        val countHex = ByteUtil.decimal2fitHex(0, 16)
        val countBytes = MyFunc.HexToByteArr(countHex)
        val cmdNoCrc = ByteUtil.combineByteArray(cmdDefault, countBytes)
        sendByte(cmdNoCrc)
    }

    /**
     * 查询控制板状态，当作心跳用
     */
    fun checkState(){
        val cmd = byteArrayOf(0x01, 0x03, 0x00, 0x21, 0x00, 0x02)
        sendByte(cmd)
    }

}